﻿#include "roundbutton.h"

#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QLinearGradient>

RoundButton::RoundButton(QString strFace, QGraphicsItem *parent):
    QGraphicsWidget(parent), m_strFace(strFace)
{
    setAcceptHoverEvents(true);
    setCacheMode(DeviceCoordinateCache);
    setVisible(false);
}

RoundButton::~RoundButton()
{

}

QPainterPath RoundButton::shape() const
{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}

void RoundButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(widget);

    // 绘制按钮图形
    bool down = option->state & QStyle::State_Sunken;
    QRectF r = boundingRect();
    QLinearGradient grad(r.topLeft(), r.bottomRight());
    grad.setColorAt(down ? 1 : 0, option->state & QStyle::State_MouseOver ? Qt::white : Qt::lightGray);
    grad.setColorAt(down ? 0 : 1, Qt::darkGray);
    painter->setPen(Qt::darkGray);
    painter->setBrush(grad);
    painter->drawEllipse(r);
    QLinearGradient grad2(r.topLeft(), r.bottomRight());
    grad2.setColorAt(down ? 1 : 0, Qt::black);
    grad2.setColorAt(down ? 0 : 1, Qt::lightGray);
    painter->setPen(Qt::NoPen);
    painter->setBrush(grad2);
    if (down)
        painter->translate(2, 2);
    painter->drawEllipse(r.adjusted(5, 5, -5, -5));
    QFont font("楷体", 25); font.setBold(true);
    QPen pen(QColor(241, 218, 145));
    painter->setFont(font);
    painter->setPen(pen);
    if (down)
        painter->translate(2, 2);
    painter->drawText(QRect(-40, -20, 100, 100), m_strFace);
}

void RoundButton::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
    emit pressed();
    update();
}

void RoundButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
    update();
}

QRectF RoundButton::boundingRect() const
{
    return QRectF(-65, -65, 130, 130);
}

